#!/usr/bin/env python
# coding=utf8
# Last Change: 2010-05-10 17:16:50

from database import Account, Message, DelayedMessage

from google.appengine.ext import db
from google.appengine.api import xmpp

from datetime import datetime, tzinfo, timedelta
import logging

def send_notify(content, gtalk):
  success = False
  while not success:
    status = xmpp.send_message(gtalk, content)
    success = (status == xmpp.NO_ERROR)

def send_notify_to_all(content, except_list):
  if except_list.__class__ != list:
    except_list = [except_list]
  for a in Account.all():
    if a.name not in except_list and not a.name.endswith('_login') and xmpp.get_presence(a.gtalk):
      success = False
      while not success:
        status = xmpp.send_message(a.gtalk, content)
        success = (status == xmpp.NO_ERROR)

def send_message_to_all(message, except_list):
  if except_list.__class__ != list:
    except_list = [except_list]
  for a in Account.all():
    if a.name in except_list or a.name.endswith('_login'):
      pass
    elif xmpp.get_presence(a.gtalk):
      str = format_message(message)
      ap = None
      if message.tag:
        q = db.GqlQuery('SELECT * FROM AccessPoint WHERE user = :1 AND tag = :2', a, message.tag)
        if q.count(1) == 1:
          ap = q.get().ap
      success = False
      while not success:
        status = xmpp.send_message(a.gtalk, str, ap)
        success = (status == xmpp.NO_ERROR)
    else:
      delayed_message = DelayedMessage(user=a.name, message=message, time=message.time)
      db.put(delayed_message)

def format_raw_message(sender, to, tag, content, time):
  str = '\n'
  str += '** from: %s\n' % sender
  if to and len(to) > 0:
    line = '** to: ' 
    for t in to:
      line += '%s, ' % t
    str += line[0:-2]
    str += '\n'
  if tag:
    str += '** tag: %s\n' % tag
  local_tz = TimeZone(8, 'GMT+8')
  utc_tz = TimeZone(0, 'GMT+0')
  local_time = time.replace(tzinfo = utc_tz).astimezone(local_tz)
  str += local_time.strftime('** %H:%M:%S, %b %d\n')
  str += '\n'
  str += content
  return str
  
def format_message(message):
  return format_raw_message(message.sender, message.to, message.tag, message.content, message.time)

class TimeZone(tzinfo):
  def __init__(self, hours, name):
    self.__offset = timedelta(hours = hours)
    self.__name = name
  def utcoffset(self, dt):
    return self.__offset
  def tzname(self, dt):
    return self.__name
  def dst(self, dt):
    return timedelta(0)

